/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.com.minam.service;

import java.awt.print.Pageable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import pe.com.minam.beans.InfoLugar;
import pe.com.minam.daorepository.InfoLugarDao;
import pe.com.minam.util.ParameterProperties;

/**
 *
 * @author Willian
 */
@Service
public class InfoAireService {

    private static final Logger logger = Logger.getLogger(InfoAireService.class.getName());

    @Autowired
    private InfoLugarDao infoLugarDao;

    @Autowired
    private ParameterProperties parameterProperties;

    public String getDataForTableHorarios(String lugar) {
        List<InfoLugar> ltaInfoLugar = null;
        String rpta = "";
        try {
            ltaInfoLugar = infoLugarDao.getPorLugar(Integer.parseInt(lugar), new PageRequest(0, parameterProperties.MAX_ROWS)).getContent();
            String filas = "";
            for (InfoLugar info : ltaInfoLugar) {
                String row = parameterProperties.data_show
                        .replace("[FECHA]", info.getFecha())
                        .replace("[HORA]", info.getHora())
                        .replace("[VALOR_MP25]", info.getMp2_5() != null ? info.getMp2_5() : "")
                        .replace("[VALOR_MP10]", info.getMp10() != null ? info.getMp10() : "")
                        .replace("[VALOR_SO2]", info.getSo2() != null ? info.getSo2() : "")
                        .replace("[VALOR_NO2]", info.getNo2() != null ? info.getNo2() : "")
                        .replace("[VALOR_CO]", info.getCo() != null ? info.getCo() : "")
                        .replace("[VALOR_O3]", info.getO3() != null ? info.getO3() : "");
                filas += row;
            }
            logger.log(Level.INFO, "TABLE HORARIOS: {0}",(parameterProperties.thead_show+filas+parameterProperties.tbody_show));
            return parameterProperties.thead_show+filas+parameterProperties.tbody_show;

        } catch (Exception ex) {
            rpta = "error";
            logger.log(Level.INFO, "Error Table ShowHorarios: {0}", ex);
        }
        return rpta;
    }

    public String getDataForTable(String lugar) {

        List<InfoLugar> ltaInfoLugar = null;
        String rpta = "";
        try {
            ltaInfoLugar = infoLugarDao.getPorLugar(Integer.parseInt(lugar), new PageRequest(0, parameterProperties.MAX_ROWS)).getContent();
            double media_mp25 = 0;
            double media_mp10 = 0;
            double media_so2 = 0;
            double media_no2 = 0;
            double media_co = 0;
            double media_o3 = 0;

            int div_mp25 = 0;
            int div_mp10 = 0;
            int div_so2 = 0;
            int div_no2 = 0;
            int div_co = 0;
            int div_o3 = 0;

            for (InfoLugar info : ltaInfoLugar) {

                if (info.getMp2_5() != null) {
                    media_mp25 += Double.parseDouble(info.getMp2_5());
                    div_mp25++;
                }
                if (info.getMp10() != null) {
                    media_mp10 += Double.parseDouble(info.getMp10());
                    div_mp10++;
                }
                if (info.getSo2() != null) {
                    media_so2 += Double.parseDouble(info.getSo2());
                    div_so2++;
                }
                if (info.getNo2() != null) {
                    media_no2 += Double.parseDouble(info.getNo2());
                    div_no2++;
                }
                if (info.getCo() != null) {
                    media_co += Double.parseDouble(info.getCo());
                    div_co++;
                }
                if (info.getO3() != null) {
                    media_o3 += Double.parseDouble(info.getO3());
                    div_o3++;
                }
            }

            rpta = parameterProperties.ULTIMOS_REGISTROS
                    .replace("[FECHA]", (new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date()) + " hrs."))
                    .replace("[VALOR_MP25]", String.valueOf(redondear((media_mp25 / div_mp25), 2)))
                    .replace("[VALOR_MP10]", String.valueOf(redondear((media_mp10 / div_mp10), 2)))
                    .replace("[VALOR_SO2]", String.valueOf(redondear((media_so2 / div_so2), 2)))
                    .replace("[VALOR_NO2]", String.valueOf(redondear((media_no2 / div_no2), 2)))
                    .replace("[VALOR_CO]", String.valueOf(redondear((media_co / div_co), 2)))
                    .replace("[VALOR_O3]", String.valueOf(redondear((media_o3 / div_o3), 2)));

        } catch (Exception ex) {
            rpta = "error";
            logger.log(Level.INFO, "Error Ultimos registros: " + ex);
        }

        return rpta;
    }

    private double redondear(double numero, int digitos) {
        {
            int cifras = (int) Math.pow(10, digitos);
            return Math.rint(numero * cifras) / cifras;
        }
    }

    public String getDataForGraphic(String tipo, String lugar) {
        String json = "{ 'info': {";
        json += "'cols': [";
        json += "{'label': 'hora', 'type': 'string'},";
        json += "{'label': 'valor', 'type': 'number'},";
        json += "{'label': 'nivel', 'type': 'string', 'role': 'style'},";
        json += "{'label': 'nivel', 'type': 'string', 'role': 'tooltip', 'p': { 'html': true } }]";

        List<InfoLugar> ltaInfoLugar = null;
        Integer idLugar = Integer.parseInt(lugar);
        logger.log(Level.INFO, "Procediendo a consultar, idLugar: {0} \tTipo: {1}", new Object[]{idLugar, tipo});

        ltaInfoLugar = infoLugarDao.getPorLugar(idLugar, new PageRequest(0, 15)).getContent();

        if (ltaInfoLugar != null && ltaInfoLugar.size() > 0) {
            json += ",'rows': [";
            String jsonC = "";
            for (InfoLugar aux : ltaInfoLugar) {

                String val = "";
                String color = "";
                String texto = "";
                if (tipo.equalsIgnoreCase("mp2_5")) {
                    val = aux.getMp2_5() != null ? convertNumber(aux.getMp2_5()) : "1";
                    color = aux.getMp2_5() != null ? "#2eae00" : "#b4b4b4";
                    texto = (aux.getMp2_5() != null ? "<strong>" + aux.getMp2_5() + " &micro;g&#8260;m<sup>3</sup></strong><br><em>" + aux.getFecha() + "</em>" : "no disponible<br><em>" + aux.getFecha() + "</em>");
                } else if (tipo.equalsIgnoreCase("mp10")) {
                    val = (aux.getMp10() != null ? convertNumber(aux.getMp10()) : "1");
                    color = aux.getMp10() != null ? "#2eae00" : "#b4b4b4";
                    texto = (aux.getMp10() != null ? "<strong>" + aux.getMp10() + " &micro;g/m<sup>3</sup>N</strong><br><em>" + aux.getFecha() + "</em>" : "no disponible<br><em>" + aux.getFecha() + "</em>");
                } else if (tipo.equalsIgnoreCase("so2")) {
                    val = (aux.getSo2() != null ? convertNumber(aux.getSo2()) : "1");
                    color = aux.getSo2() != null ? "#2eae00" : "#b4b4b4";
                    texto = (aux.getSo2() != null ? "<strong>" + aux.getSo2() + " ppbv</strong><br><em>" + aux.getFecha() + "</em>" : "no disponible<br><em>" + aux.getFecha() + "</em>");
                } else if (tipo.equalsIgnoreCase("no2")) {
                    val = (aux.getNo2() != null ? convertNumber(aux.getNo2()) : "1");
                    color = aux.getNo2() != null ? "#2eae00" : "#b4b4b4";
                    texto = (aux.getNo2() != null ? "<strong>" + aux.getNo2() + " ppbv</strong><br><em>" + aux.getFecha() + "</em>" : "no disponible<br><em>" + aux.getFecha() + "</em>");
                } else if (tipo.equalsIgnoreCase("co")) {
                    val = (aux.getCo() != null ? convertNumber(aux.getCo()) : "1");
                    color = aux.getCo() != null ? "#2eae00" : "#b4b4b4";
                    texto = (aux.getCo() != null ? "<strong>" + aux.getCo() + " ppbv</strong><br><em>" + aux.getFecha() + "</em>" : "no disponible<br><em>" + aux.getFecha() + "</em>");
                } else if (tipo.equalsIgnoreCase("o3")) {
                    val = (aux.getO3() != null ? convertNumber(aux.getO3()) : "1");
                    color = aux.getO3() != null ? "#2eae00" : "#b4b4b4";
                    texto = (aux.getO3() != null ? "<strong>" + aux.getO3() + " ppmv</strong><br><em>" + aux.getFecha() + "</em>" : "no disponible<br><em>" + aux.getFecha() + "</em>");
                }
                jsonC = "{'c':[{'v':'" + aux.getFecha() + " " + aux.getHora() + "'},{'v': " + val + "},{'v':'" + color + "'},{'v':'" + texto + "'}]}";
                json += jsonC + ",";
            }
            json = json.substring(0, json.length() - 1);
            json += "]},'datetime': '" + (new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date())) + " hrs.','status': 0}";
        } else {
            json += "},'datetime': '" + (new SimpleDateFormat("yyyy-MM-dd hh:mm").format(new Date())) + " hrs.','status': 1}";
        }
        return json;
    }

    private String convertNumber(String number) {
        String newNumber = "";
        try {
            newNumber = String.valueOf(Integer.parseInt(number) + 10);
        } catch (Exception ex) {
            double aux = Double.parseDouble(number) + 10;
            String text = String.valueOf(aux);
            newNumber = String.valueOf(Integer.parseInt(text.substring(0, text.indexOf("."))));
        }
        return newNumber;
    }
}
